package com.angel.bo.file.service.impl;

import com.angel.bo.file.param.MultipartFileParam;
import com.angel.bo.file.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.Map;

/**
 * @Author: Haibo.Mei [Haibo.Mei@ge.com]
 * @Description:
 * @Date: 11:29 2018/2/28
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService{


    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Value("${breakpoint.upload.dir}")
    private String finalDirPath;


    /**
     * 上传块文件
     *
     * @param param
     * @return
     */
    @Override
    public ResponseEntity uploadFile(MultipartFileParam param) {

        try{
            Object object = stringRedisTemplate.opsForValue().get(param.getIdentifier() + param.getChunkNumber());
            if(null != object){
                return ResponseEntity.ok("此块存在");
            }
            Object complete = stringRedisTemplate.opsForValue().get(param.getIdentifier());
            if(null != complete){
                log.info("上传文件成功了！");
                return ResponseEntity.ok("文件都存在了");
            }
            String fileName = param.getFilename();
            String uploadDirPath = finalDirPath;
            File tmpFile = new File(uploadDirPath, fileName);
            RandomAccessFile accessTmpFile = new RandomAccessFile(tmpFile, "rw");
            long offset = param.getChunkSize() * (param.getChunkNumber()-1);
            //定位到该分片的偏移量
            accessTmpFile.seek(offset);
            //写入该分片数据
            accessTmpFile.write(param.getFile().getBytes());
            // 释放
            accessTmpFile.close();
            stringRedisTemplate.opsForValue().set(param.getIdentifier() + param.getChunkNumber(), "true");


            stringRedisTemplate.opsForHash().put(param.getIdentifier()+"",param.getChunkNumber()+"",param.getCurrentChunkSize()+"");


            Map<Object, Object> fileMap =  stringRedisTemplate.opsForHash().entries(param.getIdentifier());

            long totalFileSize = 0;
            for (Object v : fileMap.values()) {
                totalFileSize = totalFileSize + Long.valueOf(v.toString());
            }
            if(totalFileSize == param.getTotalSize()){
                stringRedisTemplate.opsForValue().set(param.getIdentifier() , "true");
            }
            complete = stringRedisTemplate.opsForValue().get(param.getIdentifier());
            if(null != complete){
                log.info("上传文件成功了！开始保存文件");
            }


        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.status(300).body("上传文件失败了");
        }

        return ResponseEntity.ok("上传文件成功了");
    }

    /**
     * 检查文件是否上传成功过
     *
     * @param param
     * @return
     */
    @Override
    public ResponseEntity checkUploadedFile(MultipartFileParam param) {
        Object object = stringRedisTemplate.opsForValue().get(param.getIdentifier() + param.getChunkNumber());
        if(null == object){
            return ResponseEntity.status(300).body("不存在此块");
        }
        boolean have = Boolean.valueOf(object.toString());
        if(have){
            return ResponseEntity.ok("此块存在");
        }
        return ResponseEntity.status(300).body("不存在此块");

    }
}
